package org.example.Thread;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:定时器
 * User:Lenovo
 * Date:2022-04-09
 * Time:14:41
 */
class MyTask implements Comparable<MyTask>{
    private Runnable runnable;//任务具体要干啥
    private long time;//任务具体啥时候干,保存任务要执行的毫秒级时间戳

    public MyTask(Runnable runnable, long delay) {//after是一个时间间隔,不是绝对的时间戳的值
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    public void run(){
        runnable.run();
    }
    public long gettime(){
        return time;
    }
    @Override
    public int compareTo(MyTask o){
        //到底谁减谁,才是一个时间小的在前?背下来
        return (int) (this.time - o.time);
    }
}
class MyTimer{
    //定时器内部能够存放多个任务
    private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();
    public void schedule(Runnable runnable,long delay){
        MyTask task = new MyTask(runnable,delay);
        queue.put(task);
        //每次任务插入成功之后,都唤醒一下扫描线程,让线程重新检查一下队首的任务看是否时间到要执行
        synchronized (locker){
            locker.notify();
        }
    }
    private Object locker = new Object();

    public MyTimer(){
        java.lang.Thread t = new java.lang.Thread(() ->{
            while (true){
                try {
                    //先取出队首元素
                    MyTask task = queue.take();
                    //再比较一下看看当前这个任务时间到了没有???
                    long curtime = System.currentTimeMillis();
                    if(curtime < task.gettime()){
                        //时间没到,把任务加会队列
                        queue.put(task);
                        //指定一个等待时间
                        synchronized (locker){
                            locker.wait(task.gettime() - curtime);
                        }
                    }else {
                        //时间到了,执行任务
                        task.run();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}
public class Demo17 {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("hello world");
            }
        },3000);
        System.out.println("hello main");
    }
}
